$(function () {
    //用户编码验证
    $('#userCode').blur(validateUserCode)
    //用户名验证
    $('#userName').blur(validateUserName)
    //用户密码验证
    $('#userPassword').blur(validateUserPassword)
    // 重复密码验证
    $('#userRemi').blur(validateRePassword)
    //生日验证
    $('#birthday').blur(validateBirthday)
    //电话验证
    $('#phone').blur(validatePhone)
    //地址验证
    $('#address').blur(validateAddress)
    //表单提交
    $('.addForm').submit(async function (e) {
        e.preventDefault()
        //判断当前的表单验证是否通过
        let f1 = await validateUserCode()
        let f2 = await validateUserName()
        let f3 = validateUserPassword()
        let f4 = validateRePassword()
        let f5 = validateBirthday()
        let f6 = await validatePhone()
        let f7 = validateAddress()
        let flag = f1 & f2 & f3 & f4 & f5 & f6 & f7
        if (flag === 0) {
            return alert('请正确填写用户信息')
        }
        //提交表单进行增加用户操作
        addUser()
    })
})


/**
 * 新增用户信息的函数
 * @date 2021-05-10
 * @returns {any}
 */
async function addUser() {
    //准备参数
    let options = {
        url: 'http://146.56.230.35:3007/users/createUser',
        type: 'POST',
        data: {
            userCode: $('#userCode').val(),
            userName: $('#userName').val(),
            userPassword: $('#userPassword').val(),
            gender: $('.gender').val(),
            phone: $('#phone').val(),
            userRole: $('.userRole:checked').val(),
            birthday: $('#birthday').val(),
            address: $('#address').val(),
        },
    }
    //发起请求
    let res = await request(options)
    console.log(res)
    if (res.code !== 200) {
        return alert(res.msg)
    }
    //新增用户成功，跳转到用户列表页面
    location = 'userList.html'
}


/**
 * 用户编码验证
 * @date 2021-05-10
 * @returns {any}
 */
async function validateUserCode() {
    let userCode = $('#userCode')
    userCode[0].className = ''
    let v = userCode.val()
    let div = userCode.parent()
    let span = userCode.next()
    span.empty()
    //判断空
    if (!v) {
        div[0].className = 'error'
        span.html('用户编码不能为空')
        return false
    }
    //数字字母下划线6-12位
    let reg = /^[$\w]{6,12}$/
    if (!reg.test(v)) {
        div[0].className = 'error'
        span.html('用户编码由数字、字母、_、$组成6-12位')
        return false
    }
    //验证唯一
    let flag = await getUserByCode(v)
    if (flag) {
        div[0].className = 'error'
        span.html('用户编码被占用了')
        return false
    }
    div[0].className = 'ok'
    span.html('用户编码正确')
    return true
}


/**
 * 用户名验证
 * @date 2021-05-10
 * @returns {any}
 */
async function validateUserName() {
    let userName = $('#userName')
    userName[0].className = ''
    let v = userName.val()
    let div = userName.parent()
    let span = userName.next()
    span.empty()
    //判断空
    if (!v) {
        div[0].className = 'error'
        span.html('用户名不能为空')
        return false
    }
    //全英文或全汉字2-12位
    let reg = /^([\u4e00-\u9fa5]{2,12})$|^([a-zA-Z]{2,12})$/
    if (!reg.test(v)) {
        div[0].className = 'error'
        span.html('用户名全英文或全汉字2-12位')
        return false
    }
    //验证唯一
    let flag = await getUserByUserName(v)
    if (flag) {
        div[0].className = 'error'
        span.html('用户名码被占用了')
        return false
    }
    div[0].className = 'ok'
    span.html('用户名正确')
    return true
}


/**
 * 用户密码验证
 * @date 2021-05-10
 * @returns {any}
 */
function validateUserPassword() {
    let userPassword = $('#userPassword')
    userPassword[0].className = ''
    let v = userPassword.val()
    let div = userPassword.parent()
    let span = userPassword.next()
    span.empty()
    // 1.非空
    if (!v) {
        div[0].className = 'error'
        span.html('密码不能为空')
        return false
    }
    //2.6-20位
    let n = v.length
    if (n > 20 || n < 6) {
        div[0].className = 'error'
        span.html('密码长度6 - 12 位')
        return false
    }
    // 3.必须包含
    let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_$(){%},;'
    //判断v中的字符是否有str中的字符，false表示没有
    let flag = false
    for (let i = 0; i < n; i++) {
        let code = v[i]
        if (str.indexOf(code) >= 0) {
            flag = true
            break
        }
    }
    if (!flag) {
        div[0].className = 'error'
        span.html('密码包含大小字母_$(){%},;的任意一个')
        return false
    }
    div[0].className = 'ok'
    span.html('密码正确')
    return true
}


/**
 * 重复密码验证
 * @date 2021-05-10
 * @returns {any}
 */
function validateRePassword() {
    let userRemi = $('#userRemi')
    let v = userRemi.val()
    let div = userRemi.parent()
    div[0].className = ''
    let span = userRemi.next()
    span.empty()
    let flag = validateUserPassword()
    if (!flag) {
        div[0].className = 'error'
        span.html('请正确填写密码')
        return false
    }
    if (v !== $('#userPassword').val()) {
        div[0].className = 'error'
        span.html('两次密码不一致')
        return false
    }
    div[0].className = 'ok'
    span.html('重复密码正确')
    return true
}


/**
 * 生日验证
 * @date 2021-05-10
 * @returns {any}
 */
function validateBirthday() {
    let birthday = $('#birthday')
    let v = birthday.val().trim()
    let parent = birthday.parent()
    let span = birthday.next()
    span.empty()
    //判断非空
    if (!v) {
        parent.removeClass('ok').addClass('error')
        span.html('生日不能为空')
        return false
    }
    //判断是否符合格式yyyy-mm-dd
    let reg = /^\d{1,4}-\d{2}-\d{2}$/
    if (!reg.test(v)) {
        parent.removeClass('ok').addClass('error')
        span.html('生日的格式是yyyy-mm-dd')
        return false
    }
    let arr = v.split('-')
    arr.map((item) => {
        item = parseInt(item)
    })
    //截取年
    let year = arr[0]
    let now = new Date().getFullYear()
    if (year > now || year < 0) {
        parent.removeClass('ok').addClass('error')
        span.html(`生日的年份必须在0-${now}之间`)
        return false
    }
    //截取月
    let month = arr[1]
    if (month > 12 || month < 1) {
        parent.removeClass('ok').addClass('error')
        span.html(`生日的月份必须在1-12之间`)
        return false
    }
    //截取日
    let day = arr[2]
    let date = 28
    //判断闰年
    if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
        date = 29
    }
    let maxDate = [31, date, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if (day < 1 || day > maxDate[month - 1]) {
        parent.removeClass('ok').addClass('error')
        span.html(`生日的日期必须在1-${maxDate[month - 1]}之间`)
        return false
    }
    parent.removeClass('error').addClass('ok')
    span.html('生日正确')
    return true
}


/**
 * 电话验证
 * @date 2021-05-10
 * @returns {any}
 */
async function validatePhone() {
    let phone = $('#phone')
    let v = phone.val().trim()
    let parent = phone.parent()
    let span = phone.next()
    span.empty()
    //判断非空
    if (!v) {
        parent.removeClass('ok').addClass('error')
        span.html('电话不能空')
        return false
    }
    //规则
    let reg = /^1[3456789]\d{9}$/
    if (!reg.test(v)) {
        parent.removeClass('ok').addClass('error')
        span.html('电话号码非法')
        return false
    }
    // 唯一
    let flag = await getUserByPhone(v)
    if (flag) {
        parent.removeClass('ok').addClass('error')
        span.html('电话号码被占用')
        return false
    }
    parent.removeClass('error').addClass('ok')
    span.html('电话正确')
    return true
}


/**
 * 地址验证
 * @date 2021-05-10
 * @returns {any}
 */
function validateAddress() {
    let address = $('#address')
    let v = address.val().trim()
    let parent = address.parent()
    let span = address.next()
    span.empty()
    //判断非空
    if (!v) {
        parent.removeClass('ok').addClass('error')
        span.html('地址不能空')
        return false
    }
    parent.removeClass('error').addClass('ok')
    span.html('地址正确')
    return true
}

//通过用户编码获得用户信息 返回0表示用户编码可用，返回1表示不可用
async function getUserByCode(v) {
    let options = {
        url: 'http://146.56.230.35:3007/users/getUserByUserCode',
        type: 'GET',
        data: {
            userCode: v
        },
    }
    let res = await request(options)
    console.log(res)
    if (res.code !== 200) {
        return 0
    }
    if (res.user) {
        return 1
    }
    return 0
}

//通过用户名获得用户信息 返回0表示用户名可用，返回1表示不可用
async function getUserByUserName(v) {
    let options = {
        url: 'http://146.56.230.35:3007/users/getUserByUserName',
        type: 'GET',
        data: {
            userName: v
        },
    }
    let res = await request(options)
    console.log(res)
    if (res.code !== 200) {
        return 0
    }
    if (res.user) {
        return 1
    }
    return 0
}

//通过电话获得用户信息，返回0表示用户名可用，返回1表示不可用
async function getUserByPhone(v) {
    let options = {
        url: 'http://146.56.230.35:3007/users/getUserByPhone',
        type: 'GET',
        data: {
            phone: v
        },
    }
    let res = await request(options)
    console.log(res)
    if (res.code !== 200) {
        return 0
    }
    if (res.user) {
        return 1
    }
    return 0
}